layui.use(['customUtil','upload','laydate'], function () {
    var customUtil = layui.customUtil;
    var table = layui.table;
    var layer = layui.layer;
    var form = layui.form;
    var upload = layui.upload;
    var laydate = layui.laydate;
    var book = {
        _constant: {
            api: {
                queryBookTypes:"/bookType/bookType/list",
                queryBooks:"/book/book/list",
                addBook:"/book/book/addBook",
                editBook:"/book/book/editBook",
                deleteBook:"/book/book/deleteBook"
            },
            bookTypeList: [],
        },

        _init: function () {
            let _this = this;
            _this._bind();
            _this._initRender();
            _this._beforeRenderTable();
        },

        _initRender:function(){
            let _this = this;
            laydate.render({
               elem: '#search_book_publish_date'
            });
            laydate.render({
               elem: '#add_book_publish_date'
            });
            laydate.render({
               elem: '#edit_book_publish_date'
            });
            form.render();
            _this._uploadImage("add_image_upload",_this._constant.api.addBook,"add_book_confirm_btn","add");
            _this._uploadImage("edit_image_upload",_this._constant.api.editBook,"edit_book_confirm_btn","edit");
        },

        _bind: function () {
            let _this = this;
            $("#add_book_btn").on("click", function () {
                _this._addBook();
            });
            $("#add_book_confirm_btn").on("click", function () {
               // _this._addBookConfirm();
               layer.msg("封面必需");
            });
             $("#add_book_quit_btn").on("click", function () {
                _this._closeAllLayer("template_add");
            });
//            $("#edit_book_confirm_btn").on("click", function () {
//                _this._editBookConfirm();
//            });
             $("#edit_book_quit_btn").on("click", function () {
                _this._closeAllLayer("template_edit");
            });
            $("#search_confirm_btn").on("click", function () {
                _this._renderTable();
            });
        },

        _closeAllLayer:function(id){
            $("#"+id).hide();
            layer.closeAll();
        },

        _addBook:function(){
            $("#template_add").show();
            layer.open({
              id: "addBookTypeLayer",
              type: 1,
              area: ['500px'],
              content: $('#add_book_form'),
              closeBtn: false
            });
        },

        _uploadImage:function(elem,url,bindElem,optType){
            let _this = this;
            upload.render({
                elem: '#'+elem,
                url: url,
                auto: false,
                accept:"file",
                size: 50*1024,
                field: 'file',
                bindAction: '#'+bindElem,
                before: function(obj){
                    if(!_this._addParamCheck(optType)){
                        return false;
                    }
                    layer.load(); //上传loading
                    this.data={
                        'bookName':$("#"+optType+"_book_name").val(),
                        'bookPrice':$("#"+optType+"_book_price").val(),
                        'bookTypeId':$("#"+optType+"_book_type").val(),
                        'bookCount':$("#"+optType+"_book_count").val(),
                        'bookPublish':$("#"+optType+"_book_publish").val(),
                        'bookPublishDate':$("#"+optType+"_book_publish_date").val(),
                        'bookIntroduction':$("#"+optType+"_book_introduction").val()
                    };
                    if(optType === "edit"){
                        this.data["bookId"] = $("#book_id").val();
                    }
                },
                done: function (res) {
                    layer.closeAll();
                    if(res.success && res.success==="true"){
                        _this._closeAllLayer("template_"+optType);
                    }
                    layer.msg(res.msg);
                    _this._renderTable();
                    console.log(res);
                }
            });
        },

        _addParamCheck: function(type){
            if(!$("#"+type+"_book_name").val()){
                layer.msg("书籍名称必填");
                return false;
            }
            if(!$("#"+type+"_book_price").val()){
                layer.msg("图书价格必填");
                return false;
            }
            if(!$("#"+type+"_book_count").val()){
                layer.msg("图书数量必填");
                return false;
            }
            if(!$("#"+type+"_book_type").val()){
                layer.msg("图书类别必填");
                return false;
            }
            if(!$("#"+type+"_book_publish").val()){
                layer.msg("出版商必填");
                return false;
            }
            if(!$("#"+type+"_book_publish_date").val()){
                layer.msg("出版日期必填");
                return false;
            }
            return true;
        },

        _addBookTypeConfirm:function(){
            let _this = this;
            let bookTypeName = $("#book_type_name_add").val();
            let borrowDays = $("#borrow_days_add").val();
            if(!bookTypeName){
                layer.msg("类别名称必填");
                return false;
            }
            if(!borrowDays){
                layer.msg("可借天数必填");
                return false;
            }
            let param = {
                "bookTypeName":bookTypeName,
                "borrowDays":borrowDays
            };
            customUtil.post(_this._constant.api.addBookType, param, function (data) {
                if (data.success) {
                    _this._closeAllLayer("template_add");
                    layer.msg(data.msg);
                    _this._renderTable();
                } else {
                    layer.alert(data.messages, {
                        title: '操作失败'
                    })
                }
            });
        },

        _addBookTypeQuit:function(){
            layer.closeAll();
        },

        _beforeRenderTable:function(){
            let _this = this;
            customUtil.get(_this._constant.api.queryBookTypes, function (data) {
                if (data.code == "0") {
                    _this._constant.bookTypeList = data.data;
                    _this._renderTable();
                    _this._tableTool();
                    _this._initOptions();
                } else {
                    layer.alert(data.messages, {
                        title: '系统异常'
                    })
                }
            });
        },

        _initOptions:function(){
            let _this = this;
            let bookTypeList = _this._constant.bookTypeList;
            let html = '<option value="">请选择</option>'
            for (let i = 1; i < bookTypeList.length; i++) {
                let item = bookTypeList[i];
                html += '<option value="'+item.bookTypeId+'">'+item.bookTypeName+'</option>'
            }
            $("#search_book_type").html(html);
            $("#add_book_type").html(html);
            $("#edit_book_type").html(html);
            form.render();//重新渲染
        },

        _renderTable: function () {
            let _this = this;
            //执行一个 table 实例
            let param = _this._getTableQueryParam();
            table.render({
                elem: '#bookTypeTable',
                url: _this._constant.api.queryBooks, //数据接口
                method: 'POST', //如果无需自定义HTTP类型，可不加该参数
                contentType: 'application/json',
                where: param,
                request: {
                   pageName: 'page', //页码的参数名称，默认：page
                   limitName: 'pageSize' //每页数据量的参数名，默认：limit
                },
                title: '',
                page: true,//开启分页
                totalRow: false,//开启合计行
                cols: [[ //表头
                    {field: 'bookName', title: '图书名称'},
                    {field: 'bookPrice', title: '图书价格'},
                    {field: 'bookTypeId', title: '图书类别', templet:function (d) {
                        let bookTypeList = _this._constant.bookTypeList;
                        let html = '';
                        for (let i = 0; i < bookTypeList.length; i++) {
                            let item = bookTypeList[i];
                            if(item.bookTypeId.toString() === d.bookTypeId){
                                html = item.bookTypeName;
                                break;
                            }
                        }
                        return html;
                    }},
                    {field: 'bookCount', title: '图书数量'},
                    {field: 'bookPublish', title: '出版商'},
                    {field: 'bookPublishDate', title: '出版日期'},
                    {field: 'bookIntroduction', title: '图书简介'},
                    {field: 'bookImagePath', title: '图书封面'},
                    {field: 'createTime', title: '创建时间',templet:function (d) {
                        if(d.createTime){
                            return d.createTime.replace("T"," ").replace("Z"," ");
                        }
                        return d.createTime;
                    }},
                    {field: 'updateTime', title: '更新时间',templet:function (d) {
                        if(d.updateTime){
                            return d.updateTime.replace("T"," ").replace("Z"," ");
                        }
                        return d.updateTime;
                    }},
                    {fixed: 'right', title:'操作', toolbar: '#bookType_table_tool_bar', width:150}
                ]]
            });
        },

        _getTableQueryParam: function(){
            let _this = this;
            let param = {
                "bookName":$("#search_book_name").val(),
                "bookType":$("#search_book_type").val(),
                "bookPublishDate":$("#search_book_publish_date").val()
            };

            return param;
        },

         _tableTool: function () {
            let _this = this;
            //监听行工具事件
            table.on('tool(bookType_table_tool_bar_filter)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                let data = obj.data, //获得当前行数据
                layEvent = obj.event; //获得 lay-event 对应的值
                if (layEvent === 'edit') {
                    _this._editBook(data);
                } else if (layEvent === 'delete') {
                   _this._deleteBook(data);
                }
            });
        },

         _editBook: function (data) {
            $("#template_edit").show();
            $("#book_id").val(data.bookId);
            $("#edit_book_name").val(data.bookName);
            $("#edit_book_price").val(data.bookPrice);
            $("#edit_book_type").val(parseInt(data.bookTypeId));
            $("#edit_book_count").val(data.bookCount);
            $("#edit_book_publish").val(data.bookPublish);
            $("#edit_book_publish_date").val(data.bookPublishDate);
            $("#edit_book_introduction").val(data.bookIntroduction);
            let _this = this;
             layer.open({
              id: "editBookLayer",
              type: 1,
              area: ['500px'],
              content: $('#edit_book_form'),
              closeBtn: false
            });
        },

         _editBookConfirm:function(){
            let _this = this;
            let bookTypeName = $("#book_type_name_edit").val();
            let borrowDays = $("#borrow_days_edit").val();
            let bookTypeId = $("#book_type_id").val();
            if(!bookTypeName){
                layer.msg("类别名称必填");
                return false;
            }
            if(!borrowDays){
                layer.msg("可借天数必填");
                return false;
            }
            let param = {
                "bookTypeName":bookTypeName,
                "borrowDays":borrowDays,
                "bookTypeId":bookTypeId
            };
            customUtil.post(_this._constant.api.editBookType, param, function (data) {
                if (data.success) {
                    _this._closeAllLayer("template_edit");
                    layer.msg(data.msg);
                    _this._renderTable();
                } else {
                    layer.alert(data.messages, {
                        title: '操作失败'
                    })
                }
            });
        },

        _deleteBook: function (data) {
            let _this = this;
            layer.confirm('确认删除？', {
              btn: ['确定','取消'] //按钮
            }, function(){
                let param = {
                    "bookId" : data.bookId
                };
                customUtil.post(_this._constant.api.deleteBook, param, function (data) {
                    if (data.success) {
                        layer.msg(data.msg);
                        _this._renderTable();
                    } else {
                        layer.alert(data.messages, {
                            title: '操作失败'
                        })
                    }
                });
            }, function(){
                 layer.closeAll();
            });
        },
    };

    book._init();
});